/*
 * @Author: zw 775925302@qq.com
 * @Date: 2023-03-04 14:29:19
 * @LastEditors: zw 775925302@qq.com
 * @LastEditTime: 2023-03-18 21:21:22
 * @FilePath: /vue-element-plus-admin/src/config/axios/index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { service } from './service'

import { config } from './config'

const { default_headers } = config

const requestReq = (option: any) => {
  const { url, method, params, data, headersType, responseType } = option
  return service({
    url: url,
    method,
    params,
    data,
    responseType: responseType,
    headers: {
      'Content-Type': headersType || default_headers
    }
  })
}


const serviceReq = (option: any) => {
  const { url, method, params, data, headersType, responseType } = option;
  return service({
    url: url,
    method,
    params, //get
    data, //post
    responseType: responseType,
    headers: {
      "Content-Type": headersType || default_headers,
    },
  });
};

function awaitWrap<T, U = any>(
  promise: Promise<T>
): Promise<[T | null, U | null]> {
  return promise
    .then<[T, null]>((data: T) => [data, null])
    .catch<[null, U]>((err) => [null, err]);
}

var request = async (option: any) => {
  const {method, params} = option;
  var _method = method.toUpperCase();
  if (_method == "GET" || _method == "DELETE") {
    var [res, err] = await awaitWrap(serviceReq(option));
    if (res) {
      return [res.data, err];
    }
    return [res, err];
  } else if (_method == "POST" || _method == "PUT" ) {
    var _option = Object.assign(option);
    _option.data = params;
    _option.params = {};
    var [res, err] = await awaitWrap(serviceReq(_option));
    if (res) {
      return [res.data, err];
    }
    return [res, err];
  }

  return [null, "没有定义method:" + method + "方法处理"]
};


export default {
  get: async <T = any>(option: any) => {
    const res = await requestReq({ method: 'GET', ...option })
    return res.data as unknown as T
  },
  post: async <T = any>(option: any) => {
    const res = await requestReq({ method: 'POST', ...option })
    return res.data as unknown as T
  },
  delete: async <T = any>(option: any) => {
    const res = await requestReq({ method: 'DELETE', ...option })
    return res.data as unknown as T
  },
  put: <T = any>(option: any) => {
    return requestReq({ method: 'put', ...option }) as unknown as T
  },
  download: async <T = any>(option: any) => {
    const res = await request({ method: 'GET', responseType: 'blob', ...option })
    return res as unknown as Promise<T>
  },
  upload: async <T = any>(option: any) => {
    option.headersType = 'multipart/form-data'
    const res = await request({ method: 'POST', ...option })
    return res as unknown as Promise<T>
  },
  request,
}
